package com.hyq.learn.common.aop;

import com.google.common.base.Stopwatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author heyuqin
 * @date 2024/12/26 10:14
 */
@Aspect
@Component
public class MethodTimeCostAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(MethodTimeCostAspect.class);

    @Pointcut("@annotation(com.hyq.learn.common.aop.TimeCostLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        String name = joinPoint.getSignature().getDeclaringTypeName() + "#" + joinPoint.getSignature().getName();
        Stopwatch stopwatch = Stopwatch.createStarted();
        Object proceed = joinPoint.proceed();
        LOGGER.info("method:{},cost time:{}ms", name, stopwatch.elapsed(TimeUnit.MILLISECONDS));
        return proceed;
    }
}
